<template>
  <div class="amap-page-container">
    <el-amap map-style="amap://styles/62009be025f187dd3eafe327d2e55b8e" :zoom="realZoom"
             view-mode="2D" @init="initMap" class="amap-demo" :center="center"
    >
      <el-amap-control-tool-bar :visible="true" position="LB"></el-amap-control-tool-bar>
      <el-amap-marker v-for="(marker, index) in markers"
        :key="index"
        :position="marker"
      />
      <el-amap-control-geolocation :visible="showGeolocation"
        @complete="getLocation"
        :markerOptions="{color: 'red'}"
        :zoomToAccuracy="true"
        ref="geolocation"
        :enableHighAccuracy="true"
      />
    </el-amap>
  </div>
</template>

<script>


export default {
  name: 'GaoDeMap',
  data() {
    return {
      // 高德地图实例
      map: undefined,
      defaultZoom: 14
    }
  },
  props: {
    markers: {
      type: Array,
      required: false,
      default() {
        return []
      }
    },
    center: {
      type: Array,
      required: false,
      default() {
        return [121.59996, 31.197646]
      }
    },
    singleMarker: {
      type: Boolean,
      required: false,
      default: true
    },
    showGeolocation: {
      type: Boolean,
      required: false,
      default: false
    }
  },
  computed: {
    propsName() {
      return { ...this.defaultPropsName, ...this.props }
    },
    realZoom() {
      return this.zoom || this.defaultZoom
    }
  },
  watch: {
    map: {
      handler() {
        if (this.singleMarker && this.markers.length > 0) {
          let location = this.markers[0]
          this.map.setCenter([location.lng, location.lat]) //设置地图中心点
        } else {
          const geolocation = this.$refs.geolocation.$$getInstance()
          if (geolocation) {
            geolocation.getCurrentPosition()
          }
        }
        // 设置缩放级别
        this.map.setZoom(this.realZoom)
      },
      immediate: false
    }
  },
  methods: {
    initMap(map) {
      this.map = map
    },
    getLocation(poi) {
      let location = poi.position
      this.map.setZoomAndCenter(this.realZoom, [location.lng, location.lat]) //设置地图中心点
    }
  },
  created() {
    console.log('map-show init')
  }
}
</script>

<style scoped>
.amap-demo {
  padding: 0;
  margin: 0;
  width: 100%;
  height: 300px;
}
</style>
